﻿<!-- pdf 预览 -->
<template>
    <div>
        <canvas ref="pdfCanvas" class="pdf-canvas"></canvas>

        <div v-if="state.isLoading || state.isRendering" class="loading-overlay">
            <div class="spinner"></div>
            <p v-if="state.isLoading">正在加载PDF...</p>
            <p v-else>正在渲染页面...</p>
        </div>
        <div v-if="state.loadError" class="error-message">
            <p>{{ state.loadError }}</p>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, onUnmounted } from 'vue';
import * as pdfjsLib from 'pdfjs-dist';
import 'pdfjs-dist/web/pdf_viewer.css';
import { usePdfStore } from '@/stores/usePdfStore';
const pdfStore = usePdfStore();

const pdfCanvas = ref(null);

// 配置pdfjsWorker路径
pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf.js';

const { url, pageNum } = defineProps({
    url: {
        type: String,
        require: true,
    },
    pageNum: {
        type: Number,
    },
});

const $emits = defineEmits(['initPdfPage', 'pdfContainerSize']);

// 使用reactive管理其他状态
const state = reactive({
    totalPages: 0,
    annotations: [],
    isDrawing: false,
    startPoint: { x: 0, y: 0 },
    endPoint: { x: 0, y: 0 },
    isLoading: true,
    loadError: null,
    isRendering: false,
});

// 使用let声明pdfDoc
let pdfDoc = null;
let currentRenderTask = null;

// 渲染当前页PDF
const renderPage = async num => {
    if (!pdfDoc || state.isRendering) return;

    // 设备比例
    const devicePixelRatio = window.devicePixelRatio;
    // console.log(devicePixelRatio, 'devicePixelRatio');

    try {
        state.isRendering = true;

        // 如果有正在进行的渲染任务，取消它
        if (currentRenderTask) {
            currentRenderTask.cancel();
        }

        const page = await pdfDoc.getPage(num);
        let scale = '1';
        pdfStore.setScale('1');
        const viewport = page.getViewport({ scale: scale });

        // 设置canvas尺寸
        const canvas = pdfCanvas.value;
        const context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        // 调整容器尺寸以适应PDF
        pdfCanvas.value.style.width = `${canvas.width}px`;
        pdfCanvas.value.style.height = `${canvas.height}px`;

        $emits('pdfContainerSize', { width: `${canvas.width}px`, height: `${canvas.height}px` });
        // 渲染PDF到canvas
        const renderContext = {
            canvasContext: context,
            viewport: viewport,
        };

        currentRenderTask = page.render(renderContext);
        await currentRenderTask.promise;

        currentRenderTask = null;
    } catch (error) {
        if (error.name !== 'RenderingCancelledException') {
            console.error('渲染PDF页面时出错:', error);
            state.loadError = '渲染页面时出错';
        }
    } finally {
        state.isRendering = false;
    }
};

// 加载PDF文件
const loadPdf = async () => {
    try {
        state.isLoading = true;
        state.loadError = null;
        // 加载PDF文档
        alert(1);
        pdfDoc = await pdfjsLib.getDocument(url).promise;
        alert(2);

        state.totalPages = pdfDoc.numPages;
        $emits('initPdfPage', { current: pageNum, total: state.totalPages });
        await renderPage(1);
    } catch (error) {
        alert(error,'9999')
        console.error('加载PDF文件时出错:', error);
        state.loadError = '加载PDF文件失败，请检查URL是否正确';
    } finally {
        state.isLoading = false;
    }
};
onMounted(() => {
    loadPdf();
});

watch(
    () => pageNum,
    async () => {
        await renderPage(pageNum);
    }
);
</script>

<style scoped lang="scss"></style>
